#!/usr/bin/python

import re
import xml.etree.ElementTree as ET
from numbers_changer import Numbers_changer
from descriptor_wmbt_format import Descriptor_wmbt_format

class Parser_wmbt_format:
  def __init__(self, addDescription):
    self.addDescription = addDescription
    self.changer = Numbers_changer()
    self.descriptor = Descriptor_wmbt_format()
    self.fractionFinder = re.compile("([1-9]\d{0,5}[\.,][0]?[1-9]{1,2})|([0][\.,][0]?[1-9]{1,2})")

  def parse(self, inputFileName, outputFileName):
    xmlTree = ET.ElementTree(file = inputFileName)
    root = xmlTree.getroot()
    sentences = root[0]

    outputFile = open(outputFileName, "w")

    for s in sentences:
      sentBuff = []
      for w in s:
        if w.tag  == "tok":
            text = w[0].text.encode("utf-8")
            tags = w[1][1].text
            sentBuff.append( (text, tags) )

      sentText = self.processSentence(sentBuff)
      outputFile.write( sentText )
      outputFile.write("\n")
    outputFile.close()


  def processSentence(self, sentBuff):
    result = []
    skip = 0
    for i in xrange( len(sentBuff) ):
	if skip > 0:
            skip -= 1
            continue

        text = sentBuff[i][0]
        tags = sentBuff[i][1]
        if self.isFraction(text + sentBuff[min(len(sentBuff)-1, i+1)][0] + sentBuff[min(len(sentBuff)-1, i+2)][0]):
	    #handling of fraction
	    decimalPart = sentBuff[min(len(sentBuff)-1, i+2)][0] 
	    text = self.changer.change(text, ["num", "sg", "nom", "m3"])
	    text += " i "
	    if decimalPart[0] == '0':
              text += self.changer.change(decimalPart[1], ["num", "sg", "nom", "m3"])
            else:
              text += self.changer.change(decimalPart, ["num", "sg", "nom", "m3"])
              
            if len(decimalPart) == 2:
		if decimalPart[1] == '2' or decimalPart[1] == '3' or decimalPart[1] == '4':
			text += " setne"
		else:
			text += " setnych"
	    elif len(decimalPart) == 1:	
		if decimalPart == '2' or decimalPart == '3' or decimalPart == '4':
			text += " dziesietne"
		else:	
			text += " dziesietnych"
	    
	    #removing from sentBuff
            skip = 2    		
        elif self.isNumber(text):
            if text[0] == "-":
              result.append("minus ")
              text = text[1:]
            if i > 0:
              previousChar = sentBuff[(i-1)][0]
            else:
              previousChar = ""
            text = self.rollNumber(text, tags, sentBuff[(i+1):], previousChar)    
        
        result.append(text + " ")

    return "".join(result)


  def rollNumber(self, text, tags, sentBuff, previousChar):
    for t in sentBuff:
        form = t[1].split(":")[0]
        if form == "subst" or form == "depr":
            if t[0] == "rok" or t[0] == "roku" or t[0] == "rokiem" or t[0] == "rokowi":
              if previousChar == "o":
                tags = "adj:sg:loc:m3"
              elif previousChar == "w":
                tags = "adj:sg:loc:m3"
              elif previousChar == "z":
                tags = "adj:sg:inst:m3"
              else:
                tags = t[1].replace(form, "adj")
            else:
              tags = t[1].replace(form, "num")
            break

    tagsStr = tags
    tags = tags.split(":")
    number = self.changer.change(text, tags)
    if self.addDescription == True:
      extended_desc = " ("+self.descriptor.describe(tags)+")"
      tags_desc = "["+tagsStr+"]"
    else:
      tags_desc = ""
    return number + tags_desc

  def isFraction(self, text):
    if self.fractionFinder.search(text):
      return True
    else:
      return False

  def isNumber(self, string):
    try:
      float(string)
      return True
    except ValueError:
      return False

# ------------------------
if __name__ == "__main__":
  pass

